package cn.yeyiu.netonlinevideo.parser.video;

import androidx.lifecycle.MutableLiveData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.parser.Parser;
import cn.yeyiu.util.MediaUtil;
import cn.yeyiu.util.ThreadUtil;
import cn.yeyiu.util.VideoUtil;
import cn.yeyiu.util.bean.MediaData;
import cn.yeyiu.util.bean.VideoInfo;

public class LocalParser extends Parser {

    private final Map<String, List<VideoInfo>> videoListLdMap;
    private int curIndex;

    public LocalParser(SourceData source) {
        super(source);
        videoListLdMap = new HashMap<>();
    }

    @Override
    public Object getBaseData(String type, int pageIndex) {
        curIndex = pageIndex;

        if (type.equals("anime")) {
            return VideoUtil.getRandomCountVideos(type, source.pageSize);
        }
        // get data from cache
        List<VideoInfo> sumVideos = videoListLdMap.get(type);

        // first get
        if (sumVideos == null) {
            sumVideos = VideoUtil.getOtherVideoList(type);
            videoListLdMap.put(type, sumVideos);
        }
        return sumVideos;
    }

    @Override
    public int getMaxCount(Object data) {
        List<VideoInfo> sumVideos =(List<VideoInfo>) data;

        int pageCount;
        if (sumVideos.get(0).type.equals("anime")) {
            pageCount = 2;
        } else {
            pageCount = sumVideos.size() / source.pageSize
                    + (sumVideos.size() % source.pageSize == 0 ? 0 : 1);
        }
        return pageCount;
    }

    @Override
    public List<MediaData> getDataList(Object data, String type) {
        List<VideoInfo> sumVideos =(List<VideoInfo>) data;

        List<MediaData> videoInfos = new ArrayList<>();
        MediaData mediaData;
        VideoInfo videoInfo;
        for (int i = curIndex * source.pageSize, count = source.pageSize;
             i < sumVideos.size() && count > 0;
             i++, count--
        ){
            videoInfo = sumVideos.get(i);
            mediaData = new MediaData();

            MediaUtil.fixLocalVideoInfo(videoInfo);
            mediaData.wrap(videoInfo);
            videoInfos.add(mediaData);
        }
        return videoInfos;
    }
}
